package com.ziki.framework.wicket.markup.repeater.data;

import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.ziki.framework.wicket.markup.html.navigation.paging.FwPageable;

public class FwPageableDataProvider<T extends Serializable> implements IDataProvider<T> {
    private static final long serialVersionUID = 1L;
    private final FwPageable<T> pageable;
    private List<T> list;
    private transient long cachedCount;

    public FwPageableDataProvider(FwPageable<T> pageable) {
        if (pageable == null) {
            throw new IllegalArgumentException("argument [pageable] cannot be null");
        }
        this.list = Collections.<T> emptyList();
        // this.list = new ArrayList<T>();
        this.pageable = pageable;
        clearCachedCount();
    }

    public List<T> getData() {
        return this.list;
    }

    public Iterator<? extends T> iterator(long first, long count) {
        this.list = this.pageable.getPageList(first, count);
        return this.list.listIterator();
    }

    public long size() {
        // return this.cachedCount;
        return getCachedCount();
    }

    public IModel<T> model(T object) {
        return new Model<T>(object);
    }

    public void clearCachedCount() {
        this.cachedCount = -1L;
    }

    public void setCachedCount(long Count) {
        this.cachedCount = Count;
    }

    public long getCachedCount() {
        if (this.cachedCount < 0L) {
            this.cachedCount = this.pageable.getDataCount();
            // throw new
            // IllegalStateException("getCountCache() called when cache was not set");
        }
        return this.cachedCount;
    }

    public boolean isCountCached() {
        return (this.cachedCount >= 0L);
    }

    public void detach() {
        this.list.clear();
        clearCachedCount();
    }
}
